from datetime import datetime
import tkinter as tk


def calculator():
    root, record, result, button, log = ui()  # 绘制ui界面
    menu(record, result, button)    # 功能绑定
    root.mainloop() # 窗口循环事件


def ui():
    root = tk.Tk()  # 创建窗口对象
    root.title("简易计算器") # 设置标题
    root.geometry("350x420+500+150")    # 设置界面大小
    root.resizable(False,False) # 固定界面大小
    root["background"] = "#f9f1ec"  # 设置界面颜色
    font_result = ('宋体', 20)    # 设置字体
    font_normal = ('宋体', 16)
    font_log = ('宋体', 12)

    record = tk.StringVar() # 创建显示框，用于显示输入记录
    record.set("")
    tk.Label(root, textvariable=record, font=font_normal, height=4, width=30, justify=tk.LEFT, anchor=tk.SE) \
        .grid(row=1, column=1, columnspan=4, pady=1)

    result = tk.StringVar() # 创建显示框，用于显示当前输入内容
    result.set("0")
    tk.Label(root, textvariable=result, font=font_result, height=2, width=23, justify=tk.LEFT, anchor=tk.SE) \
        .grid(row=2, column=1, columnspan=4, pady=1)

    button_C = tk.Button(root, text='C', font=font_normal, width=6, relief=tk.FLAT, bg="#ffffff")   # 设置按钮控件
    button_B = tk.Button(root, text='🔙', font=font_normal, width=6, relief=tk.FLAT, bg="#ffffff")
    button_yu = tk.Button(root, text='%', font=font_normal, width=6, relief=tk.FLAT, bg="#ffffff")
    button_chu = tk.Button(root, text='/', font=font_normal, width=6, relief=tk.FLAT, bg="#ffffff")
    button_C.grid(row=3, column=1, padx=5, pady=4)  # 按钮控件布局
    button_B.grid(row=3, column=2, padx=5, pady=4)
    button_yu.grid(row=3, column=3, padx=5, pady=4)
    button_chu.grid(row=3, column=4, padx=5, pady=4)

    button_7 = tk.Button(root, text='7', font=font_normal, width=6, relief=tk.FLAT, bg="#ffffff")
    button_8 = tk.Button(root, text='8', font=font_normal, width=6, relief=tk.FLAT, bg="#ffffff")
    button_9 = tk.Button(root, text='9', font=font_normal, width=6, relief=tk.FLAT, bg="#ffffff")
    button_x = tk.Button(root, text='*', font=font_normal, width=6, relief=tk.FLAT, bg="#ffffff")
    button_7.grid(row=4, column=1, padx=5, pady=4)
    button_8.grid(row=4, column=2, padx=5, pady=4)
    button_9.grid(row=4, column=3, padx=5, pady=4)
    button_x.grid(row=4, column=4, padx=5, pady=4)

    button_4 = tk.Button(root, text='4', font=font_normal, width=6, relief=tk.FLAT, bg="#ffffff")
    button_5 = tk.Button(root, text='5', font=font_normal, width=6, relief=tk.FLAT, bg="#ffffff")
    button_6 = tk.Button(root, text='6', font=font_normal, width=6, relief=tk.FLAT, bg="#ffffff")
    button_sub = tk.Button(root, text='-', font=font_normal, width=6, relief=tk.FLAT, bg="#ffffff")
    button_4.grid(row=5, column=1, padx=5, pady=4)
    button_5.grid(row=5, column=2, padx=5, pady=4)
    button_6.grid(row=5, column=3, padx=5, pady=4)
    button_sub.grid(row=5, column=4, padx=5, pady=4)

    button_1 = tk.Button(root, text='1', font=font_normal, width=6, relief=tk.FLAT, bg="#ffffff")
    button_2 = tk.Button(root, text='2', font=font_normal, width=6, relief=tk.FLAT, bg="#ffffff")
    button_3 = tk.Button(root, text='3', font=font_normal, width=6, relief=tk.FLAT, bg="#ffffff")
    button_add = tk.Button(root, text='+', font=font_normal, width=6, relief=tk.FLAT, bg="#ffffff")
    button_1.grid(row=6, column=1, padx=5, pady=4)
    button_2.grid(row=6, column=2, padx=5, pady=4)
    button_3.grid(row=6, column=3, padx=5, pady=4)
    button_add.grid(row=6, column=4, padx=5, pady=4)

    button_0 = tk.Button(root, text='0', font=font_normal, width=14, relief=tk.FLAT, bg="#ffffff")
    button_point = tk.Button(root, text='.', font=font_normal, width=6, relief=tk.FLAT, bg="#ffffff")
    button_equ = tk.Button(root, text='=', font=font_normal, width=6, relief=tk.FLAT, bg="#ffffff")
    button_0.grid(row=7, column=1, padx=5, pady=4, columnspan=2)
    button_point.grid(row=7, column=3, padx=5, pady=4)
    button_equ.grid(row=7, column=4, padx=5, pady=4)

    log = tk.StringVar()    # 底部欢迎提示语
    log.set("欢迎使用简易计算器")
    tk.Label(root, textvariable=log, font=font_log, height=1, width=23, justify=tk.CENTER, ) \
        .grid(row=8, column=1, columnspan=4, pady=4)

    button = {"button_C": button_C, "button_B": button_B, "button_yu": button_yu, "button_chu": button_chu,
              "button_7": button_7, "button_8": button_8, "button_9": button_9, "button_x": button_x,
              "button_4": button_4, "button_5": button_5, "button_6": button_6, "button_sub": button_sub,
              "button_1": button_1, "button_2": button_2, "button_3": button_3, "button_add": button_add,
              "button_0": button_0, "button_point": button_point, "button_equ": button_equ
              }
    return [root, record, result, button, log]  #将需要的控件等信息返回出去


def menu(record, result, button):
    def click_button(num):  # 点击按钮
        global flag
        if flag == 1:
            result.set(num)
            record.set(record.get() + num)
        elif flag == 2:
            result.set(num)
            record.set("" + num)
            flag = 1

    def calcul_equ(): # 点击等于号
        global flag, back_flag
        try:
            result1 = eval(record.get())
            result.set(result1)
        except:
            result.set("error")

        flag = 2
        back_flag = 2
        save_log()

    def calcul_clear(): # 点击清除键
        result.set("0")
        record.set("")

    def calcul_back():  # 点击回退键
        global back_flag
        if back_flag != 2:
            num = result.get()[:-1]
            result.set(num)
            record.set(record.get()[:-1] + num)
        else:
            result.set("0")
            record.set("")
            back_flag = 1

    def save_log(): # 保存日志
        log_text = record.get() + "=" + result.get() + "\n"
        current_time = str(datetime.now())
        with open("log.txt", mode="a+") as log_file:
            log_file.write(current_time+"\t"+log_text)

    button["button_1"].config(command=lambda: click_button('1'))    # 按钮绑定操作事件
    button["button_2"].config(command=lambda: click_button('2'))
    button["button_3"].config(command=lambda: click_button('3'))
    button["button_4"].config(command=lambda: click_button('4'))
    button["button_5"].config(command=lambda: click_button('5'))
    button["button_6"].config(command=lambda: click_button('6'))
    button["button_7"].config(command=lambda: click_button('7'))
    button["button_8"].config(command=lambda: click_button('8'))
    button["button_9"].config(command=lambda: click_button('9'))
    button["button_0"].config(command=lambda: click_button('0'))
    button["button_point"].config(command=lambda: click_button('.'))
    button["button_add"].config(command=lambda: click_button('+'))
    button["button_sub"].config(command=lambda: click_button('-'))
    button["button_x"].config(command=lambda: click_button('*'))
    button["button_chu"].config(command=lambda: click_button('/'))
    button["button_yu"].config(command=lambda: click_button('%'))

    button["button_equ"].config(command=calcul_equ)
    button["button_C"].config(command=calcul_clear)
    button["button_B"].config(command=calcul_back)


if __name__ == '__main__':
    flag = 1    # 用于辅助完善等于键，按下之后输入会刷新
    back_flag = 1   # 用于辅助完善回退键，按下会清除最后一个输入的内容
    calculator()
